package br.com.dojo.controller;

import java.util.ArrayList;
import java.util.List;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import br.com.dojo.bean.Servico;
import br.com.dojo.service.ServicoService;

@Controller
@RequestMapping(value = "/servico/**", method = RequestMethod.GET)
public class ServicoController {
	private static final Logger logger = LoggerFactory
			.getLogger(ServicoController.class);
	@Autowired
	private ServicoService servicoService;

	// private List<Servico> listaServicos;

	public ServicoController() {
		// listaServicos = new ArrayList<Servico>();
		// listaServicos.add(new Servico(1, "Risos", 40, true));
	}

	@RequestMapping(value = "/servico/list", method = RequestMethod.GET)
	public String list(ModelMap modelMap) {
		modelMap.addAttribute("servicos", servicoService.listarServicos());
		return "/servico/list";
	}

	@RequestMapping(value = "/servico/show/{codigo}", method = RequestMethod.GET)
	public String show(@PathVariable("codigo") Long id, ModelMap modelMap) {
		// modelMap.addAttribute("contato", contatoDao.find(id));

		modelMap.addAttribute("servico", servicoService.getById(id));

		return "servico/show";
	}

	@RequestMapping(value = "/servico", method = RequestMethod.GET)
	public String create(Servico servico, BindingResult result) {

		return "servico/create";
	}

	@RequestMapping(value = "/servico/criar", method = RequestMethod.POST)
	public String criar(@Valid Servico servico, BindingResult result) {

		if (result.hasErrors()) {
			result.getAllErrors();
			return "servico/create";
		}

		servicoService.persist(servico);
		return "redirect:/servico/list";
	}

	@RequestMapping(value = "/servico/atualizar/{id}", method = RequestMethod.GET)
	public String updateForm(@PathVariable("id") Long id, ModelMap modelMap) {

		modelMap.addAttribute("servico", servicoService.getById(id));

		return "servico/update";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String update(@Valid Servico servico, BindingResult result) {
		if (result.hasErrors())
			return "servico/update"; //
		servicoService.merge(servico);

		return "redirect:/servico/list";
	}

	@RequestMapping(value = "/servico/remover/{id}", method = RequestMethod.DELETE)
	public String delete(@PathVariable("id") Long id) {
		servicoService.remove(id);
		return "redirect:/servico/list";
	}

}
